package com.faselbaum.stalkme.activities;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.DefaultedHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.ByteArrayBuffer;

import com.faselbaum.stalkme.R;
import com.faselbaum.stalkme.models.ProfileInfo;
import com.faselbaum.stalkme.models.ProfileInfo.relationShip;
import com.faselbaum.stalkme.utils.BluetoothAccess;
import com.faselbaum.stalkme.utils.ProfileInfoStorage;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.http.AndroidHttpClient;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.graphics.Bitmap.CompressFormat;


public class ProfileSettings extends Activity
{
	
	private Activity _activity = null;
	private ImageButton _imageButtonProfilePicture = null;
	private EditText _editTextName = null;
	private TextView _textViewMACAddress = null;
	private Spinner _spinnerRelationship = null;
	private EditText _editTextShortDescription = null;
	private EditText _editTextInterests = null;
	private Button _buttonSave = null;
	private Button _buttonCancel = null;
	private Button _buttonDelete = null;
	
	private Uri _selectedImage = null;
	private Bitmap _selectedImageBitmap = null;
	
	private BluetoothAccess _btAccess = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
		setContentView(R.layout.layout_profilesettings);	
		
		_activity = this;		
		_imageButtonProfilePicture = (ImageButton)findViewById(R.id.imageButton_profilePicture);
		_editTextName = (EditText)findViewById(R.id.editText_profileName);
		_textViewMACAddress = (TextView)findViewById(R.id.textView_macAddress);
		_spinnerRelationship = (Spinner)findViewById(R.id.spinner_relationship);
		_editTextShortDescription = (EditText)findViewById(R.id.editText_shortDescription);
		_editTextInterests = (EditText)findViewById(R.id.editText_interests);
		_buttonSave = (Button)findViewById(R.id.button_save);
		_buttonCancel = (Button)findViewById(R.id.button_cancel);
		_buttonDelete = (Button)findViewById(R.id.button_deleteProfile);
		
		_btAccess = new BluetoothAccess(this);
		
		_textViewMACAddress.setText(getResources().getString(R.string.profile_macAddress) +  ": " + _btAccess.getMACAddress());
		
		_imageButtonProfilePicture.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
				photoPickerIntent.setType("image/*");
				startActivityForResult(photoPickerIntent, 100);
			}
		});
		
		_buttonSave.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				storeProfile();
			}
		});
		
		_buttonDelete.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				removeProfile();				
			}
		});
		
		ProfileInfo info = ProfileInfoStorage.getInstance().getProfile(_btAccess.getMACAddress());
		setProfile(info);
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
	    switch(requestCode)
	    { 
	        case 100:
	            if(resultCode == RESULT_OK)
	            {  
	                _selectedImage = data.getData();
	                InputStream imageStream;
					try
					{
						imageStream = getContentResolver().openInputStream(_selectedImage);
		                _selectedImageBitmap = BitmapFactory.decodeStream(imageStream);
		                _imageButtonProfilePicture.setImageBitmap(_selectedImageBitmap);
					}
					catch (FileNotFoundException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	            }
	        }
	}
	
	private boolean storeProfile()
	{
		ProfileInfo info = new ProfileInfo();
		String[] names = null;
		String firstName = null;
		String lastName = null;
		
		names = _editTextName.getText().toString().split(" ");
		if(names.length>0)
		{
			firstName = names[0];
			if(names.length>1)
			{
				lastName = "";
				for(int i=1;i<names.length;i++)
				{
					lastName += names[i];
				}
			}
		}
		
		info.setBluetoothDeviceInfo(_btAccess.getLocalDeviceInfo());
		info.setFirstName(firstName);
		info.setLastName(lastName);
		info.setRelationShip(relationShip.values()[_spinnerRelationship.getSelectedItemPosition()]);
		info.setShortDescription(_editTextShortDescription.getText().toString());
		info.setInterests(_editTextInterests.getText().toString());
		
		return ProfileInfoStorage.getInstance().storeProfileInfo(info);
	}
	
	private boolean removeProfile()
	{
		ProfileInfo info = new ProfileInfo();
		info.setBluetoothDeviceInfo(_btAccess.getLocalDeviceInfo());
		return ProfileInfoStorage.getInstance().deleteProfileInfo(info);
	}
	
	public void setProfile(ProfileInfo info)
	{
		if(info!=null)
		{
			String name = "";
			
			if(info.getFirstName()!=null) name+=info.getFirstName();
			if(info.getLastName()!=null) name+= " " + info.getLastName();
			
			if(name!=null) _editTextName.setText(name);			
			if(info.getShortDescription()!=null) _editTextShortDescription.setText(info.getShortDescription());
			if(info.getInterests()!=null) _editTextInterests.setText(info.getInterests());
			_spinnerRelationship.setSelection(info.getRelationShip().ordinal());
			
			_textViewMACAddress.setText(getResources().getString(R.string.profile_macAddress) +  ": " + info.getBluetoothDeviceInfo().getMACAddress());
		}
	}
	
}
